from django.shortcuts import render
import simplejson
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from stock import get_stock_from_ts, get_index_daily, attention_stock, common_function, global_variable, \
    selected_stock_K_line, condition_query
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job

# 定时任务
try:
    hour_t = '18,23'
    minute_t = '30'
    second_t = '0'
    # 实例化调度器
    scheduler = BackgroundScheduler()
    # 调度器使用DjangoJobStore()
    scheduler.add_jobstore(DjangoJobStore(), "default")


    # 'cron'方式循环，周一到周五day_of_week='mon-fri'，每天22:30:00执行,id为工作ID作为标记
    # @register_job(scheduler, 'cron', day_of_week='mon-sun', hour=hour_t, minute=minute_t, second=second_t,id='pre_analysis')
    @register_job(scheduler, 'cron', day_of_week='mon-fri', hour=hour_t, minute=minute_t, id='pre_analysis')  # 每天自动更新
    def test_job():
        print(get_stock_from_ts.update_all_stock_trade_info())  # 更新所有股票交易和股指信息
        print(get_stock_from_ts.update_stockbasic())
        print(get_stock_from_ts.update_company_info())


    # 监控任务
    register_events(scheduler)
    # 调度器开始
    scheduler.start()
except Exception as e:
    print(e)
    scheduler.shutdown()


# 指数页面相关函数
def index(request):
    """
        指数界面主函数，此处读取的数据必须和index.js中的响应函数对应
        cmd_class:命令类别参数。分别为update：更新股票信息命令，不返回数据集，只返回更新结果
                                     query：查询类命令，并返回数据
                                     attention：和关注相关的命令，分为添加关注、删除关注、获取关注数据、删除关注数据
        command：具体的命令参数，不同参数执行不同函数，需和前端一一对应
        :param request:
        :return:根据查询返回相关信息
    """
    if request.method == "GET":
        if request.is_ajax():
            # 更新数据菜单
            if request.GET.get("cmd_class") == "update":
                command = request.GET.getlist("command")
                result = '未更新数据'
                if command[0] == 'update_daily':  result = get_stock_from_ts.get_all_stock_daily_info()
                if command[0] == 'update_daily_basic': result = get_stock_from_ts.get_all_stock_daily_basic_info()
                if (command[0] == 'update_block_trade'): result = get_stock_from_ts.get_all_block_trade_info()
                if (command[0] == 'update_moneyflow'): result = get_stock_from_ts.get_all_moneyflow_info()
                if (command[0] == 'update_stockbasic'): result = get_stock_from_ts.update_stockbasic()
                if (command[0] == 'update_company'): result = get_stock_from_ts.update_company_info()
                if (command[0] == 'update_all_basic'): result = get_stock_from_ts.update_all_stock_trade_info()
                if (command[0] == 'update_index_daily'): result = get_stock_from_ts.get_all_index_daily_info()

                return HttpResponse(result)

            # 查询数据相关
            if request.GET.get("cmd_class") == "query":
                command = request.GET.get("command")
                if (command == 'index_daily'):
                    SSE_000001SH = get_index_daily.index_daily('000001.SH')
                    SZSE_399001SZ = get_index_daily.index_daily('399001.SZ')
                    return JsonResponse({'SSE_000001SH': SSE_000001SH, 'SZSE_399001SZ': SZSE_399001SZ}, safe=False)
                if command == 'stock_detail_info':  # 查询单个股票详细信洗
                    stock_name = request.GET.get("stock_name")
                    ts_code = request.GET.get("ts_code")
                    return render(request, 'stock/show_selected_stock.html',
                                  {"stock_name": stock_name, "ts_code": ts_code})
                if command == 'search_autofill':
                    search_txt = request.GET.get("search_txt")
                    namelist, tscodelist = common_function.searchinput_autofill(search_txt)
                    return JsonResponse((namelist, tscodelist), safe=False)

            # 关注股票相关
            if request.GET.get("cmd_class") == "attention":
                command = request.GET.get("command")
                if command == 'get_attention':  # 获取关注数据
                    is_end = request.GET.get("is_end")
                    data = attention_stock.get_stock_data(is_end)
                    return JsonResponse(data, safe=False)
                if command == 'cancel_attention':  # 取消关注、批量传入
                    ts_code_list = request.GET.get("ts_code_list")
                    ts_code_list = simplejson.loads(ts_code_list)
                    attention_stock.update_attention_state(ts_code_list, False)
                    return HttpResponse('取消关注成功')
                if command == 'afresh_attention':  # 重新关注、批量传入
                    ts_code_list = request.GET.get("ts_code_list")
                    ts_code_list = simplejson.loads(ts_code_list)
                    attention_stock.update_attention_state(ts_code_list, True)
                    return HttpResponse('重新关注成功')
                if command == 'clear_attention':  # 清除关注列表
                    is_end = request.GET.get("is_end")
                    attention_stock.clear_attention_date(is_end)
                    return HttpResponse('删除关注列表成功')
                if command == 'add_one_attention':  # 添加一个关注股票,需要按照股票名称查找股票ts代码，这个可以删掉，要确保调用时传入的是股票ts_code
                    stockname = request.GET.get("stock_name")
                    strategy = request.GET.get("strategy")
                    stockcodelist = []
                    stockcodelist.append(common_function.query_ts_code(stockname))
                    result = attention_stock.attention_stock_into_db(stockcodelist, strategy)
                    return HttpResponse(result)
                if command == 'add_list_attention':  # 添加一串股票代码
                    attention_code_list = request.GET.get("ts_code_list")
                    attention_code_list = simplejson.loads(attention_code_list)
                    strategy = request.GET.get("strategy")
                    result = attention_stock.attention_stock_into_db(attention_code_list, strategy)
                    return HttpResponse(result)

            # 数据库维护相关
            if request.GET.get("cmd_class") == "DB":
                command = request.GET.get("command")
                if command == "delete_all_stock_info":
                    res = common_function.delete_all_stock_table_infor()
                    return HttpResponse(res)

    return render(request, 'stock/index.html', )


# 查询股票信息页面相关函数
def get_selected_stock(request):
    """
     返回股票sina网K线图页面，和get_selected_stock页面关联
      :param request:
      :return: 返回股票sina网K线图，需要获取股票ts_code 和股票名称
      """
    if request.is_ajax():
        if (request.method == "GET"):
            if request.GET.get("cmd_class") == "query":
                command = request.GET.get("command")
                if command == 'K_line':  # 如果是查询K线图
                    stock_name = request.GET.get("stock_name")
                    ts_code = request.GET.get("ts_code")
                    return render(request, 'stock/show_selected_stock_K_line.html',
                                  {"stock_name": stock_name, "ts_code": ts_code})

                stockname = request.GET.get("stockname")
                if (command == 'daily'):
                    data = common_function.query_daily_by_stockname(stockname)
                    columns = common_function.get_models_verbose_name('stock', global_variable.DAILY_TABLE)
                    return JsonResponse({'columns': columns, 'data': data}, safe=False)
                if (command == 'daily_basic'):
                    data = common_function.query_daily_basic_by_stockname(stockname)
                    columns = common_function.get_models_verbose_name('stock', global_variable.DAILY_BASIC_TABLE)
                    return JsonResponse({'columns': columns, 'data': data}, safe=False)
                if (command == 'block_trade'):
                    data = common_function.query_block_trade_by_stockname(stockname)
                    columns = common_function.get_models_verbose_name('stock', global_variable.BLOCK_TRADE_TABLE)
                    return JsonResponse({'columns': columns, 'data': data}, safe=False)
                if (command == 'moneyflow'):
                    data = common_function.query_moneyflow_by_stockname(stockname)
                    columns = common_function.get_models_verbose_name('stock', global_variable.MONEYFLOW_TABLE)
                    return JsonResponse({'columns': columns, 'data': data}, safe=False)

    return HttpResponse('未获取到股票数据')


# 从sina网查询股票相关函数
def get_selected_stock_K_line(request):
    """
       从新浪和东方财富获取股票图形信息
       :param request:
       :return:
       """
    if request.is_ajax():
        if (request.method == "GET"):
            cmd = request.GET.get("request_cmd")
            if (cmd == 'chart_moneyflow'):
                ts_code = request.GET.get("ts_code")
                return HttpResponse(selected_stock_K_line.get_chart_moneyflow_from_eastmoney(ts_code))
            if (cmd == 'data_moneyflow'):
                ts_code = request.GET.get("ts_code")
                new_moneyflow = selected_stock_K_line.get_new_moneyflow(ts_code)

                return JsonResponse(new_moneyflow, safe=False)


# 条件查询页面相关函数
def condition_query_stock(request):
    """
    条件页面查询相关函数，其中参数如果是9999999999，表示无穷大
    :param request:
    :return: 查询到的股票列表
    """
    if request.method == "GET":
        if request.is_ajax():

            if request.GET.get("cmd_class") == "query":
                command = request.GET.get("command")
                if (command == "conditions"):
                    dic_conditions_list = request.GET.get("data")  # 返回一个字符串
                    dic_con = simplejson.loads(dic_conditions_list)  # 解析字符串，返回一个list
                    query_trade_date = request.GET.get("trade_date")
                    ts_code_list, name_list = condition_query.query_stock_with_conditons(query_trade_date, dic_con)

                    return JsonResponse((ts_code_list, name_list), safe=False)
                if command == 'stock_detail_info':  # 查询单个股票详细信洗
                    stock_name = request.GET.get("stock_name")
                    ts_code = request.GET.get("ts_code")
                    return render(request, 'stock/show_selected_stock.html',
                                  {"stock_name": stock_name, "ts_code": ts_code})
            if request.GET.get("cmd_class") == "attention":
                command = request.GET.get("command")

                if command == 'add_list_attention':  # 添加一串股票代码
                    attention_code_list = request.GET.get("ts_code_list")
                    attention_code_list = simplejson.loads(attention_code_list)
                    strategy = request.GET.get("strategy")
                    result = attention_stock.attention_stock_into_db(attention_code_list, strategy)
                    return HttpResponse(result)

    return render(request, 'stock/condition_query_stock.html', )
